package com.century.sjt.activity;

import android.Manifest;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.content.res.AssetFileDescriptor;
import android.graphics.Bitmap;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Vibrator;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.century.sjt.EMChat.widget.EaseAlertDialog;
import com.century.sjt.R;
import com.century.sjt.SjtHelper;
import com.century.sjt.activity.Pay.MerchantItemActivity;
import com.century.sjt.entity.Merchant;
import com.century.sjt.util.Constant;
import com.century.sjt.util.TipUtil;
import com.century.sjt.util.camera.CameraManager;
import com.century.sjt.util.decoding.CaptureActivityHandler;
import com.century.sjt.util.decoding.InactivityTimer;
import com.century.sjt.widget.TitleBar.SjtTitleBar;
import com.century.sjt.widget.ViewfinderView;
import com.easemob.chat.EMChatManager;
import com.easemob.chat.EMContactManager;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.Result;

import org.json.JSONObject;
import org.json.JSONTokener;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Vector;

//扫一扫
public class QRRecordCodeScanActivity extends BaseActivity implements SurfaceHolder.Callback {

    private ImageButton btnSys;                                     //返回按钮
    private TextView mTitle;                                        //程序标题
    private LinearLayout leftLinLayout;                             //左边的线性布局

    private CaptureActivityHandler handler;
    private ViewfinderView viewfinderView;
    private boolean hasSurface;
    private Vector<BarcodeFormat> decodeFormats;
    private String characterSet;
    private InactivityTimer inactivityTimer;
    private MediaPlayer mediaPlayer;
    private boolean playBeep;
    private static final float BEEP_VOLUME = 0.10f;
    private boolean vibrate;
    private SjtTitleBar titleBar;
    private ProgressDialog progressDialog;

    final private int REQUEST_CODE_ASK_PERMISSIONS = 123;
    private void insertDummyContactWrapper() {
        int hasWriteContactsPermission = ContextCompat.checkSelfPermission(QRRecordCodeScanActivity.this,
                Manifest.permission.CAMERA);
        if (Build.VERSION.SDK_INT >= 23){
            if (hasWriteContactsPermission != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(QRRecordCodeScanActivity.this,
                        new String[] {Manifest.permission.CAMERA},
                        REQUEST_CODE_ASK_PERMISSIONS);
                return;
            }
        }


    }
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        if (requestCode == REQUEST_CODE_ASK_PERMISSIONS){
            if (permissions[0].equals(Manifest.permission.CAMERA)
                    &&grantResults[0] == PackageManager.PERMISSION_GRANTED){
                //用户同意使用write

            }else{
                //用户不同意，自行处理即可
                finish();
            }
        }
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_qrrecord_code_scan);
        insertDummyContactWrapper();

//        mTitle= (TextView) findViewById(R.id.img_title);
//        mTitle.setText("二维码扫描");
//        btnSys= (ImageButton) findViewById(R.id.btn_sys);
////        btnSys.setImageResource(R.drawable.selector_btn_return);
//        btnSys.setClickable(false);
//        leftLinLayout= (LinearLayout) findViewById(R.id.leftLinLayout);
//        leftLinLayout.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                finish();
//                overridePendingTransition(R.animator.in_from_left, R.animator.out_to_right);
//            }
//        });

        titleBar = (SjtTitleBar) findViewById(R.id.title_bar);
        //       标题栏
//        titleBar.setLeftImageResource(R.drawable.ease_mm_title_back);
        titleBar.setLeftLayoutClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        titleBar.setTitle(getResources().getString(R.string.tab_qr_sweep));

        CameraManager.init(getApplication());
        viewfinderView = (ViewfinderView) findViewById(R.id.viewfinder_view);
        hasSurface = false;
        inactivityTimer = new InactivityTimer(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        SurfaceView surfaceView = (SurfaceView) findViewById(R.id.preview_view);
        SurfaceHolder surfaceHolder = surfaceView.getHolder();
        if (hasSurface) {
            initCamera(surfaceHolder);
        } else {
            surfaceHolder.addCallback(this);
            surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
        }
        decodeFormats = null;
        characterSet = null;

        playBeep = true;
        AudioManager audioService = (AudioManager) getSystemService(AUDIO_SERVICE);
        if (audioService.getRingerMode() != AudioManager.RINGER_MODE_NORMAL) {
            playBeep = false;
        }
        initBeepSound();
        vibrate = true;
    }

    @Override
    protected void initView() {

    }

    @Override
    protected void initEvent() {

    }

    @Override
    protected void initData() {

    }

    @Override
    protected void onPause() {
        super.onPause();
        if (handler != null) {
            handler.quitSynchronously();
            handler = null;
        }
        CameraManager.get().closeDriver();
    }

    @Override
    protected void onDestroy() {
        inactivityTimer.shutdown();
        super.onDestroy();
    }

    public void handleDecode(Result result, Bitmap barcode) {
        inactivityTimer.onActivity();
        playBeepSoundAndVibrate();
        String resultString = result.getText();
        if (resultString.equals("")) {
            Toast.makeText(QRRecordCodeScanActivity.this, "Scan failed!", Toast.LENGTH_SHORT).show();
        }else {
//            qrRecordCodeResult(resultString);
            Intent resultIntent = new Intent();
            Bundle bundle = new Bundle();
            bundle.putString("result", resultString);
//            bundle.putParcelable("bitmap", barcode);
            resultIntent.putExtras(bundle);
            this.setResult(RESULT_OK, resultIntent);
        }
        QRRecordCodeScanActivity.this.finish();
    }

    private void initCamera(SurfaceHolder surfaceHolder) {
        try {
            CameraManager.get().openDriver(surfaceHolder);
        } catch (IOException ioe) {
            return;
        } catch (RuntimeException e) {
            return;
        }
        if (handler == null) {
            handler = new CaptureActivityHandler(this, decodeFormats,
                    characterSet);
        }
    }

//    @Override
//    public boolean onCreateOptionsMenu(Menu menu) {
//        // Inflate the menu; this adds items to the action bar if it is present.
//        getMenuInflater().inflate(R.menu.menu_qrrecord_code_scan, menu);
//        return true;
//    }
//
//    @Override
//    public boolean onOptionsItemSelected(MenuItem item) {
//        // Handle action bar item clicks here. The action bar will
//        // automatically handle clicks on the Home/Up button, so long
//        // as you specify a parent activity in AndroidManifest.xml.
//        int id = item.getItemId();
//
//        //noinspection SimplifiableIfStatement
//        if (id == R.id.action_settings) {
//            return true;
//        }
//
//        return super.onOptionsItemSelected(item);
//    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        if (!hasSurface) {
            hasSurface = true;
            initCamera(holder);
        }
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {

    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        hasSurface = false;
    }

    public ViewfinderView getViewfinderView() {
        return viewfinderView;
    }

    public Handler getHandler() {
        return handler;
    }

    public void drawViewfinder() {
        viewfinderView.drawViewfinder();

    }

    private void initBeepSound() {
        if (playBeep && mediaPlayer == null) {
            // The volume on STREAM_SYSTEM is not adjustable, and users found it
            // too loud,
            // so we now play on the music stream.
            setVolumeControlStream(AudioManager.STREAM_MUSIC);
            mediaPlayer = new MediaPlayer();
            mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
            mediaPlayer.setOnCompletionListener(beepListener);

            AssetFileDescriptor file = getResources().openRawResourceFd(
                    R.raw.beep);
            try {
                mediaPlayer.setDataSource(file.getFileDescriptor(),
                        file.getStartOffset(), file.getLength());
                file.close();
                mediaPlayer.setVolume(BEEP_VOLUME, BEEP_VOLUME);
                mediaPlayer.prepare();
            } catch (IOException e) {
                mediaPlayer = null;
            }
        }
    }

    private static final long VIBRATE_DURATION = 200L;

    private void playBeepSoundAndVibrate() {
        if (playBeep && mediaPlayer != null) {
            mediaPlayer.start();
        }
        if (vibrate) {
            Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
            vibrator.vibrate(VIBRATE_DURATION);
        }
    }

    /**
     * When the beep has finished playing, rewind to queue up another one.
     */
    private final MediaPlayer.OnCompletionListener beepListener = new MediaPlayer.OnCompletionListener() {
        public void onCompletion(MediaPlayer mediaPlayer) {
            mediaPlayer.seekTo(0);
        }
    };

    //加载好友信息
    public void qrRecordCodeResult(String Src){
//                    Toast.makeText(SjtMainActivity.this, bundle.getString("result"), Toast.LENGTH_LONG).show();
                    String result = Src;
                    //判断返回字符串数据是打开网页还是加好友
                    if(result.indexOf(Constant.QRRECORD_ADDFRIEND)>=0) {
                        //判断“：”前后的字符串
                        int i = result.indexOf(':');
//                  int x = mQRCordId.indexOf(':',i+1);
                        String option = result.substring(0, i);
                        String friendId = result.substring(i + 1);
                        switch (option) {
                            case Constant.QRRECORD_ADDFRIEND:
                                qrAddfrind(friendId);
                                break;
                            default:
                                break;
                        }
                    }else if(result.indexOf(Constant.QRRECORD_SHOP_ID)>=0) {//扫描商家二维码
//                        商家身份暂不支持支付
                        String isShop = getSharedPreferences(com.century.sjt.util.Constant.TAG, Activity.MODE_PRIVATE).getString("isShop", "");
                        if("0".equals(isShop)) {
                            //判断“：”前后的字符串
                            int i = result.indexOf(':');
//                          int x = mQRCordId.indexOf(':',i+1);
                            String option = result.substring(0, i);
                            String shopId = result.substring(i + 1);
                            switch (option) {
                                case com.century.sjt.util.Constant.QRRECORD_SHOP_ID:
                                    shopDetail(shopId);
                                    break;
                                default:
                                    break;
                            }
                        }else {
                            TipUtil.showToast("商家身份暂不支持支付", QRRecordCodeScanActivity.this, 1);
                        }
                    }else if(result.indexOf(com.century.sjt.util.Constant.QRRECORD_HTTP)>=0) {
                        Intent intent = new Intent(Intent.ACTION_VIEW);
                        intent.setData(Uri.parse(result));
                        startActivity(intent);
                    }else{
                        Intent intent = new Intent(Intent.ACTION_VIEW);
                        intent.setData(Uri.parse("https://www.baidu.com/s?wd=" + result));
                        startActivity(intent);
                    }

    }

    private void qrAddfrind(final String addfriendId) {

        if(EMChatManager.getInstance().getCurrentUser().equals(addfriendId)){
            new EaseAlertDialog(QRRecordCodeScanActivity.this, R.string.not_add_myself).show();
            return;
        }

        if(SjtHelper.getInstance().getContactList().containsKey(addfriendId)){
//            提示已在好友列表中(在黑名单列表里)，无需添加
//            if(EMContactManager.getInstance().getBlackListUsernames().contains(addfriendId)){
//                new EaseAlertDialog(MainActivity.this, R.string.user_already_in_contactlist).show();
//                return;
//            }
            new EaseAlertDialog(QRRecordCodeScanActivity.this, R.string.This_user_is_already_your_friend).show();
            return;
        }

        progressDialog = new ProgressDialog(QRRecordCodeScanActivity.this);
        String stri = getResources().getString(R.string.Is_sending_a_request);
        progressDialog.setMessage(stri);
        progressDialog.setCanceledOnTouchOutside(false);
        progressDialog.show();

        new Thread(new Runnable() {
            public void run() {

                try {
                    //demo写死了个reason，实际应该让用户手动填入
                    String s = getResources().getString(R.string.Add_a_friend);
                    EMContactManager.getInstance().addContact(addfriendId, s);
                    runOnUiThread(new Runnable() {
                        public void run() {
                            progressDialog.dismiss();
                            String s1 = getResources().getString(R.string.send_successful);
                            TipUtil.showToast(s1, QRRecordCodeScanActivity.this, 1);
//                            Toast.makeText(getApplicationContext(), s1, 1).show();
                        }
                    });
                } catch (final Exception e) {
                    runOnUiThread(new Runnable() {
                        public void run() {
                            progressDialog.dismiss();
                            String s2 = getResources().getString(R.string.Request_add_buddy_failure);
                            TipUtil.showToast(s2 + e.getMessage(), QRRecordCodeScanActivity.this, 1);
//                            Toast.makeText(getApplicationContext(), s2 + e.getMessage(), 1).show();
                        }
                    });
                }
            }
        }).start();

    }

    /**
     * 获取商店详情
     * @param shopId
     */
    private void shopDetail(final String shopId) {
        TipUtil.openProgressDialog(com.century.sjt.util.Constant.APPLICATION_NAME, getResources().getString(R.string.error_please_waitting), QRRecordCodeScanActivity.this);
        StringRequest stringRequest = new StringRequest(Request.Method.POST, com.century.sjt.util.Constant.ShopDetail, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                try {
                    TipUtil.closeProgressDialog();
                    TipUtil.log("接口返回成功", response.toString(), 1);
                    JSONTokener jsonParser = new JSONTokener(response);
                    JSONObject res = (JSONObject) jsonParser.nextValue();
                    String code = res.getString("code");
                    String message = res.getString("message");
                    if (code.equals("200")) {//成功
                        JSONObject aData = res.getJSONObject("data");
                        Merchant merchant = new Merchant();
                        merchant.setShopId(aData.getString("shopId"));
                        merchant.setShopName(aData.getString("shopName"));
//                            Log.e("name",aData.getString("shopName"));
                        merchant.setLogo(aData.getString("logo"));
                        merchant.setDiscount(aData.getString("discount"));
                        merchant.setAddress(aData.getString("address"));
                        merchant.setTelephone(aData.getString("telephone"));
                        merchant.setTelephoneOne(aData.getString("telephoneOne"));
                        merchant.setMobile(aData.getString("mobile"));
                        merchant.setDesc(aData.getString("desc"));
                        merchant.setCity(aData.getString("city"));
                        merchant.setImage(aData.getString("image"));
                        merchant.setUserId(aData.getString("userId"));
                        merchant.setLastTopic(aData.getString("lastTopic"));
                        merchant.setNewGoods(aData.getString("newGoods"));
                        Intent intent = new Intent();
                        intent.setClass(QRRecordCodeScanActivity.this, MerchantItemActivity.class);
                        Bundle mBundle = new Bundle();
                        mBundle.putSerializable("Merchant", merchant);
                        intent.putExtras(mBundle);
                        intent.putExtra("shopId", shopId);
                        intent.putExtra("payType","2");
                        startActivity(intent);
                    } else {//失败
                        TipUtil.showToast(message, QRRecordCodeScanActivity.this, 1);
                    }
                } catch (Exception ex) {
                    ex.printStackTrace();
                    TipUtil.showToast(getResources().getString(R.string.error_service),QRRecordCodeScanActivity.this, 1);
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                TipUtil.showToast(getResources().getString(R.string.error_network), QRRecordCodeScanActivity.this, 1);
                TipUtil.closeProgressDialog();
            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> map = new HashMap<String, String>();
//                SharedPreferences mainSharedPreferences =getSharedPreferences(Constant.TAG, Activity.MODE_PRIVATE);
//                String userId = mainSharedPreferences.getString("userId", "");
//                map.put("loginId", userId);
                map.put("shopId",shopId);
                return map;
            }
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                SharedPreferences mainSharedPreferences =getSharedPreferences(com.century.sjt.util.Constant.TAG, Activity.MODE_PRIVATE);
                String cookie = mainSharedPreferences.getString("cookie", "");
                String rememberMeValue = mainSharedPreferences.getString("rememberMe", "");
                HashMap localHashMap = new HashMap();
                String cookieValue = cookie + ";" + rememberMeValue;
                localHashMap.put("Cookie", cookieValue);
                return localHashMap;
            }
        };
        mQueue.add(stringRequest);
    }
}
